package main

import (
	"html/template"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"

	"script-management/internal/config"
	"script-management/internal/handlers"
	"script-management/internal/services"
)

func main() {
	// 创建配置
	cfg := config.NewConfig()

	// 创建 Gin 引擎
	r := gin.Default()

	// 注册模板函数
	r.SetFuncMap(template.FuncMap{
		"hasSuffix": strings.HasSuffix,
	})

	// 加载HTML模板
	r.LoadHTMLGlob(filepath.Join(cfg.TemplateDir, "*"))

	// 设置静态文件路由
	r.Static("/static", cfg.StaticDir)

	// 初始化服务
	scriptService := services.NewScriptService(cfg.ScriptDir)
	venvService := services.NewVenvService(cfg.VenvDir)
	systemService := services.NewSystemService()
	systemService.SetScriptService(scriptService)

	// 初始化处理器
	h := handlers.NewHandler(scriptService, venvService, systemService)

	// 设置路由
	r.GET("/", h.Home)
	r.GET("/scripts", h.ManageScripts)
	r.POST("/scripts", h.AddScript)
	r.GET("/scripts/:id", h.GetScript)
	r.DELETE("/scripts/:id", h.DeleteScript)
	r.POST("/scripts/:id/run", h.RunScript)
	r.POST("/scripts/:id/stop", h.StopScript)
	r.GET("/scripts/:id/status", h.GetScriptStatus)
	r.GET("/scripts/:id/files", h.ManageFiles)
	r.POST("/scripts/:id/files/:filename", h.SaveFile)
	r.GET("/scripts/:id/download", h.DownloadScript)

	r.GET("/venvs", h.ManageVenvs)
	r.POST("/venvs", h.CreateVenv)
	r.DELETE("/venvs/:id", h.DeleteVenv)
	r.GET("/venvs/:id/packages", h.ListPackages)
	r.POST("/venvs/:id/packages", h.InstallPackage)
	r.DELETE("/venvs/:id/packages/:package", h.UninstallPackage)

	r.GET("/monitor", h.Monitor)
	r.GET("/api/system/resources", h.GetSystemResources)

	// 启动服务器
	r.Run(cfg.ServerAddr)
}
